package com.xm.security.config;

import com.xm.security.config.properties.SecurityProperties;
import com.xm.security.utils.MD5PasswordEncoder;
import com.xm.security.config.security.SecurityConfig;
import com.xm.security.exception.ExceptionAdviceHandler;
import com.xm.security.exception.ExceptionFilter;
import com.xm.security.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.HttpFirewall;

import javax.annotation.Resource;

/**
 * @author yousj
 * @since 2021/9/5
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@ConditionalOnMissingBean(WebSecurityConfigurerAdapter.class)
@EnableConfigurationProperties(SecurityProperties.class)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfigAutoConfigure {

    private final JwtUtil jwtUtil;
    private final UserDetailsService userServiceImpl; //自定义登录认证逻辑
    private final ExceptionAdviceHandler exceptionAdviceHandler;
    private final ExceptionFilter exceptionFilter;
    private final SecurityProperties securityProperties;
    @Resource
    private SecurityConfig securityConfig;

    @Bean
    @SneakyThrows
    @ConditionalOnMissingBean
    public SecurityConfig securityConfig() {
        return new SecurityConfig(jwtUtil, userServiceImpl, exceptionAdviceHandler, exceptionFilter, securityProperties);
    }

    @Bean
    @SneakyThrows
    @ConditionalOnMissingBean
    @ConditionalOnClass(SecurityConfig.class)
    public AuthenticationManager authenticationManagerBean() {
        return securityConfig.authenticationManagerBean();
    }



    @Bean
    @ConditionalOnMissingBean
    public HttpFirewall httpFirewall() {
        return new DefaultHttpFirewall();
    }

}
